﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeiBoUI.FormEx;
using System.IO;
using WeiBOAPI.Common;
using WeiBOAPI.Sina;
using WeiBoUI.ComboBoxEx;
using WeiBOAPI;

namespace KKWeiBO
{
    public partial class UserLoginFrm : FormBase
    {
        public SinaLogin SelSinaLogin { get; set; }
        public bool DoLogin { get; set; }

        public UserLoginFrm()
        {
            SelSinaLogin = null;

            InitializeComponent();

            LoadUsers();
        }

        public void LoadUsers()
        {
            if (!Directory.Exists("./Sina/"))
            {
                Directory.CreateDirectory("./Sina/");
            }
            cmbUserName.Items.Clear();
            string[] files = Directory.GetFiles("./Sina/");
            if (files.Length > 0)
            {
                foreach (string userFile in files)
                {
                    SinaLogin sinaLogin = CommonTools.ReadXml<SinaLogin>(userFile);
                    cmbUserName.Items.Add(new ComBoItemEx(sinaLogin, sinaLogin.LoginUserName));
                }
                cmbUserName.SelectedIndex = 0;
            }
            
        }

        private void kButton1_Click(object sender, EventArgs e)
        {
            this.Hide();
            new RegFrm().ShowDialog();
            LoadUsers();
            this.Show();
        }

        private void kButton2_Click(object sender, EventArgs e)
        {
            if (SelSinaLogin != null)
            {
                DoLogin = true;
                Global.Instance._g_SinaService._loginName = SelSinaLogin.LoginUserName;
                Global.Instance._g_SinaService._user_Id = SelSinaLogin.UserID;
                Global.Instance._g_SinaService._oauth_token = SelSinaLogin.OAuthTokenKey;
                Global.Instance._g_SinaService._oauth_token_secret = SelSinaLogin.OAuthTokenSecretKey;
                this.Close();
            }
            
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelSinaLogin = (SinaLogin)((ComBoItemEx)cmbUserName.SelectedItem).Value;
        }

        private void UserLoginFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (DoLogin == false)
            {
                Global.Instance.SysExit();
                Application.Exit();
            }
            
        }
    }
}
